import axios from "axios";
import { refreshTokenApi } from "../api/api";
//创建axios的示例

const service = axios.create({
  baseURL: "http://localhost:9527",
  timeout: 50000,
  headers: {
    "Content-Type": "application/json;charset=utf-8",
  },
});

// // 请求拦截器
// service.interceptors.request.use(
//   (config) => {
//     config.headers["Authorization"] = localStorage.getItem("token") || "";
//   },
//   (error) => {
//     return Promise.reject(error);
//   }
// );
service.interceptors.request.use(
  (config) => {
    if (config.url === "/refresh_token") {
      config.headers["Authorization"] = `Bearer ${localStorage.getItem(
        "refresh_token"
      )}`;
    } else {
      let token = localStorage.getItem("token");
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  async (response) => {
    console.log(response);
    let { code, data } = response.data;
    if (code === 0) {
      //成功
      let res = data;
      res?.refresh_token &&
        localStorage.setItem("refresh_token", data.refresh_token);
      res?.token && localStorage.setItem("token", data.token);

      return res;
    } else if (code === 401) {
      //Token失效
      //调用刷新token接口 保存token后  重新调用原来接口
      // re.headers.Authorization = localStorage.getItem("refresh_token");
      let result = await refreshTokenApi();
      if (result) {
        response.config.headers[
          "Authorization"
        ] = `Bearer ${localStorage.getItem("token")}`;
        //重新调用接口
        let popRes = service.request(response.config);
        return popRes;
      }
    }
    return Promise.reject(data);
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

// 导出 axios 实例
export default service;
